package com.guli.product.service;

import com.guli.common.response.Result;
import com.guli.model.product.CategoryEntity;
import com.guli.model.product.dto.CategoryDTO;
import com.guli.product.mapper.CategoryMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    //三级查询
    public List<CategoryDTO> findTreeCategoryDTO() {
        return categoryMapper.findTreeCategoryDTO();
    }

    //Stream 树状结构查询
    public List<CategoryDTO> listTreeCategoryDTO() {
        //查询所有记录
        List<CategoryEntity> categoryEntityList = categoryMapper.selectList(null);
        List<CategoryDTO> stream = categoryEntityList.stream()
                .filter((categoryEntity)->{
                    //过滤 只查询parentcid=0
                    return categoryEntity.getParentCid() == 0;
                })
                .map((categoryEntity)->{
                    //吧 categoryEntity 转成CategoryDTO
                    CategoryDTO categoryDTO=new CategoryDTO();
                    BeanUtils.copyProperties(categoryEntity, categoryDTO);
                    //得到子目录
                    categoryDTO.setChildren(getChiLdren(categoryEntity,categoryEntityList));
                   return  categoryDTO;
                }).collect(Collectors.toList());
        return stream;

        //子集查询
    }
    public List<CategoryDTO> getChiLdren(CategoryEntity  parent,List<CategoryEntity> categoryEntityList){
        List<CategoryDTO> stream =  categoryEntityList.stream()
                .filter((CategoryEntity)->{
                    return  CategoryEntity.getParentCid()==parent.getCatId();
                }).map((categoryEntity1)->{
                    CategoryDTO categoryDTO=new CategoryDTO();
                    BeanUtils.copyProperties(categoryEntity1, categoryDTO);
                    categoryDTO.setChildren(getChiLdren(categoryEntity1,categoryEntityList));
                    return categoryDTO;
                }).collect(Collectors.toList());
        if(stream.size() == 0){
                return  null;
        }
        return stream;
    }





    //新增修改
    public Result save(CategoryEntity categoryEntity){
        if(categoryEntity.getCatId()!=null){
            categoryMapper.updateById(categoryEntity);
            return new Result(true, "1", "添加分类成功");
        }else{
            categoryMapper.insert(categoryEntity);
            return new Result(true, "1", "添加分类成功");
        }
    }

    //id 查询
    public  CategoryEntity seleteByid(Long catid){
        return  categoryMapper.selectById(catid);
    }

    //删除 逻辑删除
    public Result deleteByid(Long catid){
        categoryMapper.deleteById(catid);
        return  new Result(true, "1", "逻辑删除成功");
    }
}
